// SPDX-License-Identifier: GPL-2.0
/*
 * Manage a pseudo e820map to support vpmem.
 *
 * Copyright (C) Huawei Futurewei Technologies.
 */

#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/memblock.h>
#include <linux/ioport.h>
#include <linux/sort.h>
#include <linux/of_fdt.h>
#include <linux/acpi.h>
#include <asm/vpmem.h>
#include <asm/vpmem/api.h>
#include <asm/setup.h>
#include <asm/mmu.h>
#include <linux/vpmem.h>

struct e820map e820;

void __init vpmem_set_userdef(int value)
{
}

static void __init __e820__range_add(struct e820map *e820x, u64 start, u64 size,
					 enum e820_type type)
{
	unsigned int x = e820x->nr_entries;

	if (start > ULLONG_MAX - size) {
		pr_err("e820: size: %llx is overflow\n", (unsigned long long)(size));
		return;
	}

	if (x >= ARRAY_SIZE(e820x->entries)) {
		pr_err("e820: too many entries; ignoring [mem %#010llx-%#010llx]\n",
		       (unsigned long long) start,
		       (unsigned long long) (start + size - 1));
		return;
	}

	e820x->entries[x].addr = start;
	e820x->entries[x].size = size;
	e820x->entries[x].type = type;
	e820x->nr_entries++;
}

void vpmem_update_memory_range(void)
{
	int i;

	for (i = 0; i < e820.nr_entries; i++) {
		struct e820entry *entry = &e820.entries[i];

		if (entry->type != E820_TYPE_VPMEM)
			continue;
		vpmem_add_memory_range(entry->addr >> PAGE_SHIFT,
			(entry->addr + entry->size - 1) >> PAGE_SHIFT);
	}
}

void __init e820__range_add(u64 start, u64 size, enum e820_type type)
{
	__e820__range_add(&e820, start, size, type);
}

static inline const char *e820_type_to_string(enum e820_type type)
{
	switch (type) {
	case E820_TYPE_RESERVED_KERN:
	case E820_TYPE_RAM:		return "System RAM";
	case E820_TYPE_ACPI:		return "ACPI Tables";
	case E820_TYPE_NVS:		return "ACPI Non-volatile Storage";
	case E820_TYPE_UNUSABLE:	return "Unusable memory";
	case E820_TYPE_PRAM:		return "Persistent RAM";
	case E820_TYPE_OSP_NVRAM:	return "BIOS NVRAM";
	case E820_TYPE_OSP_MEM:		return "cache";
	case E820_TYPE_PCIE_MEM:	return "mirror memory";
	case E820_TYPE_PBS:		return "pbs";
	case E820_TYPE_MEM_FAULT:	return "fault memory";
	case E820_TYPE_VPMEM:		return "Virtual Machine Memory";
	default:			return "reserved";
	}
}

void __init e820__print_table(char *who)
{
	int i;

	for (i = 0; i < e820.nr_entries; i++)
		pr_info("%s: [mem %#018Lx-%#018Lx] %s\n", who,
				e820.entries[i].addr,
				e820.entries[i].addr + e820.entries[i].size - 1,
				e820_type_to_string(e820.entries[i].type));
}

/*
 * Sanitize the BIOS e820.entries.
 *
 * Some e820 responses include overlapping entries. The following
 * replaces the original e820.entries with a new one, removing overlaps,
 * and resolving conflicting memory types in favor of highest
 * numbered type.
 *
 * The input parameter e820map points to an array of 'struct
 * e820entry' which on entry has elements in the range [0, *pnr_map)
 * valid, and which has space for up to max_nr_map entries.
 * On return, the resulting sanitized e820.entries entries will be in
 * overwritten in the same location, starting at e820map.
 *
 * The integer pointed to by pnr_map must be valid on entry (the
 * current number of valid entries located at e820map). If the
 * sanitizing succeeds the *pnr_map will be updated with the new
 * number of valid entries (something no more than max_nr_map).
 *
 * The return value from sanitize_e820.entries() is zero if it
 * successfully 'sanitized' the map entries passed in, and is -1
 * if it did nothing, which can happen if either of (1) it was
 * only passed one map entry, or (2) any of the input map entries
 * were invalid (start + size < start, meaning that the size was
 * so big the described memory range wrapped around through zero.)
 *
 *	Visually we're performing the following
 *	(1,2,3,4 = memory types)...
 *
 *	Sample memory map (w/overlaps):
 *	   ____22__________________
 *	   ______________________4_
 *	   ____1111________________
 *	   _44_____________________
 *	   11111111________________
 *	   ____________________33__
 *	   ___________44___________
 *	   __________33333_________
 *	   ______________22________
 *	   ___________________2222_
 *	   _________111111111______
 *	   _____________________11_
 *	   _________________4______
 *
 *	Sanitized equivalent (no overlap):
 *	   1_______________________
 *	   _44_____________________
 *	   ___1____________________
 *	   ____22__________________
 *	   ______11________________
 *	   _________1______________
 *	   __________3_____________
 *	   ___________44___________
 *	   _____________33_________
 *	   _______________2________
 *	   ________________1_______
 *	   _________________4______
 *	   ___________________2____
 *	   ____________________33__
 *	   ______________________4_
 */
struct change_member {
	struct e820entry *pe820; /* pointer to original e820 entry */
	unsigned long long addr; /* address for this change point */
};

static int __init cpcompare(const void *a, const void *b)
{
	struct change_member * const *app = a, * const *bpp = b;
	const struct change_member *ap = *app, *bp = *bpp;

	/*
	 * Inputs are pointers to two elements of change_point[].  If their
	 * addresses are unequal, their difference dominates.  If the addresses
	 * are equal, then consider one that represents the end of its region
	 * to be greater than one that does not.
	 */
	if (ap->addr != bp->addr)
		return ap->addr > bp->addr ? 1 : -1;

	return (ap->addr != ap->pe820->addr) - (bp->addr != bp->pe820->addr);
}

static int __init sanitize_e820_map(struct e820entry *e820map, int max_nr_map,
				     u32 *pnr_map)
{
	static struct change_member change_point_list[2*E820_X_MAX] __initdata;
	static struct change_member *change_point[2*E820_X_MAX] __initdata;
	static struct e820entry *overlap_list[E820_X_MAX] __initdata;
	static struct e820entry new_map[E820_X_MAX] __initdata;
	unsigned long current_type, last_type;
	unsigned long long last_addr;
	int chgidx;
	int overlap_entries;
	int new_map_entry;
	int old_nr, new_nr, chg_nr;
	int i;

	/* if there's only one memory region, don't bother */
	if (*pnr_map < 2)
		return -1;

	old_nr = *pnr_map;
	if (old_nr > max_nr_map) {
		pr_err("old_nr:%u should not larger than max_nr_map:%u\n", old_nr, max_nr_map);
		return -EINVAL;
	}

	/* bail out if we find any unreasonable addresses */
	for (i = 0; i < old_nr; i++) {
		if (e820map[i].addr + e820map[i].size < e820map[i].addr)
			return -1;
	}

	/* create pointers for initial change-point information (for sorting) */
	for (i = 0; i < 2 * old_nr; i++)
		change_point[i] = &change_point_list[i];

	/*
	 * record all known change-points (starting and ending addresses),
	 * omitting those that are for empty memory regions
	 */
	chgidx = 0;
	for (i = 0; i < old_nr; i++)	{
		if (e820map[i].size == 0)
			continue;

		change_point[chgidx]->addr = e820map[i].addr;
		change_point[chgidx++]->pe820 = &e820map[i];
		change_point[chgidx]->addr = e820map[i].addr + e820map[i].size;
		change_point[chgidx++]->pe820 = &e820map[i];
	}
	chg_nr = chgidx;

	/* sort change-point list by memory addresses (low -> high) */
	sort(change_point, chg_nr, sizeof(*change_point), cpcompare, NULL);

	/* create a new e820 memory map, removing overlaps */
	overlap_entries = 0;	 /* number of entries in the overlap table */
	new_map_entry = 0;	 /* index for creating new e820 map entries */
	last_type = 0;		 /* start with undefined memory type */
	last_addr = 0;		 /* start with 0 as last starting address */

	/* loop through change-points, determining affect on the new e820 map */
	for (chgidx = 0; chgidx < chg_nr; chgidx++) {
		/* keep track of all overlapping e820 entries */
		if (change_point[chgidx]->addr ==
		    change_point[chgidx]->pe820->addr) {
			/*
			 * add map entry to overlap list (> 1 entry
			 * implies an overlap)
			 */
			overlap_list[overlap_entries++] =
				change_point[chgidx]->pe820;
		} else {
			/*
			 * remove entry from list (order independent,
			 * so swap with last)
			 */
			for (i = 0; i < overlap_entries; i++) {
				if (overlap_list[i] ==
				    change_point[chgidx]->pe820)
					overlap_list[i] =
						overlap_list[overlap_entries-1];
			}
			overlap_entries--;
		}
		/*
		 * if there are overlapping entries, decide which
		 * "type" to use (larger value takes precedence --
		 * 1=usable, 2,3,4,4+=unusable)
		 */
		current_type = 0;
		for (i = 0; i < overlap_entries; i++) {
			if (overlap_list[i]->type > current_type)
				current_type = overlap_list[i]->type;
		}
		/*
		 * continue building up new e820 map based on this
		 * information
		 */
		if (current_type != last_type || current_type == E820_TYPE_PRAM) {
			if (last_type != 0) {
				new_map[new_map_entry].size =
					change_point[chgidx]->addr - last_addr;
				/*
				 * move forward only if the new size
				 * was non-zero
				 */
				if (new_map[new_map_entry].size != 0) {
					if (++new_map_entry >= max_nr_map)
						break;
				}
			}
			if (current_type != 0)	{
				new_map[new_map_entry].addr =
					change_point[chgidx]->addr;
				new_map[new_map_entry].type = current_type;
				last_addr = change_point[chgidx]->addr;
			}
			last_type = current_type;
		}
	}
	/* retain count for new e820 entries */
	new_nr = new_map_entry;

	/* copy new e820 mapping into original location */
	memcpy(e820map, new_map, new_nr * sizeof(struct e820entry));
	*pnr_map = new_nr;

	return 0;
}

u64 __init __e820__range_update(struct e820map *e820x, u64 start,
					u64 size, enum e820_type old_type,
					enum e820_type new_type)
{
	u64 end;
	unsigned int i;
	u64 real_updated_size = 0;

	if (old_type == new_type) {
		pr_err("old type is same as new type:%u\n", old_type);
		return 0;
	}

	if (size > (ULLONG_MAX - start))
		size = ULLONG_MAX - start;

	end = start + size;
	pr_info("e820: update [mem %#010Lx-%#010Lx] %s ==> %s\n",
			start, end - 1,
			e820_type_to_string(old_type), e820_type_to_string(new_type));

	for (i = 0; i < e820x->nr_entries; i++) {
		struct e820entry *ei = &e820x->entries[i];
		u64 final_start, final_end;
		u64 ei_end;

		if (ei->type != old_type)
			continue;

		ei_end = ei->addr + ei->size;
		/* totally covered by new range? */
		if (ei->addr >= start && ei_end <= end) {
			ei->type = new_type;
			real_updated_size += ei->size;
			continue;
		}

		/* new range is totally covered? */
		if (ei->addr < start && ei_end > end) {
			__e820__range_add(e820x, start, size, new_type);
			__e820__range_add(e820x, end, ei_end - end, ei->type);
			ei->size = start - ei->addr;
			real_updated_size += size;
			continue;
		}

		/* partially covered */
		final_start = max(start, ei->addr);
		final_end = min(end, ei_end);
		if (final_start >= final_end)
			continue;

		__e820__range_add(e820x, final_start, final_end - final_start,
				  new_type);

		real_updated_size += final_end - final_start;

		/*
		 * left range could be head or tail, so need to update
		 * size at first.
		 */
		ei->size -= final_end - final_start;
		if (ei->addr < final_start)
			continue;
		ei->addr = final_end;
	}
	return real_updated_size;
}

u64 __init e820__range_update(u64 start, u64 size, enum e820_type old_type, enum e820_type new_type)
{
	return __e820__range_update(&e820, start, size, old_type, new_type);
}

void __init request_vpmem_res_resource(void)
{
	struct resource *res_vpmem;
	unsigned int i;

	for (i = 0; i < e820.nr_entries; ++i) {
		if (e820.entries[i].type != E820_TYPE_VPMEM)
			continue;

		res_vpmem = memblock_alloc(sizeof(*res_vpmem), SMP_CACHE_BYTES);
		if (!res_vpmem) {
			pr_err("alloc vpmem request resource failed\n");
			continue;
		}

		res_vpmem->name = "Virtual Machine Memory";
		res_vpmem->start = (resource_size_t)e820.entries[i].addr;
		res_vpmem->end = (resource_size_t)(e820.entries[i].addr + e820.entries[i].size - 1);
		res_vpmem->flags = IORESOURCE_MEM;

		if (request_resource(&iomem_resource, res_vpmem)) {
			pr_warn("vpmem request resource failed\n");
			memblock_free_early(virt_to_phys(res_vpmem), sizeof(*res_vpmem));
		}
	}
}

u64 e820__mapped_find(u64 *start, enum e820_type type)
{
	int i;

	for (i = 0; i < e820.nr_entries; i++) {
		struct e820entry *entry = &e820.entries[i];

		if (type && entry->type != type)
			continue;

		if (start && entry->addr >= *start) {
			*start = entry->addr;
			return entry->size;
		}
	}
	return 0;
}

u64 vpmem__mapped_find(u64 *start, enum e820_type type)
{
	int i;

	for (i = 0; i < e820.nr_entries; i++) {
		struct e820entry *entry = &e820.entries[i];

		if (type && entry->type != type)
			continue;

		if (start && entry->addr >= *start) {
			*start = entry->addr;
			return entry->size;
		}
	}
	return 0;
}
EXPORT_SYMBOL_GPL(vpmem__mapped_find);

static void __init vpmem_memblock_remove(void)
{
	int i;
	u64 end;

	/*
	 * The bootstrap memblock region count maximum is 128 entries
	 * (INIT_MEMBLOCK_REGIONS), but EFI might pass us more E820 entries
	 * than that - so allow memblock resizing.
	 *
	 * This is safe, because this call happens pretty late during setup,
	 * so we know about reserved memory regions already. (This is important
	 * so that memblock resizing does no stomp over reserved areas.)
	 */
	memblock_allow_resize();

	for (i = 0; i < e820.nr_entries; i++) {
		struct e820entry *entry = &e820.entries[i];

		end = entry->addr + entry->size;
		if (end != (resource_size_t)end)
			continue;

		if (entry->type == E820_TYPE_VPMEM)
			memblock_remove(entry->addr, entry->size);
	}
}

static void __init align_e820_map(struct e820entry *e820map, int nr_entries)
{
	unsigned long long align_end;
	int i;

	for (i = 0; i < nr_entries; i++) {
		if (e820map[i].type != E820_TYPE_VPMEM)
			continue;
		align_end = ALIGN_DOWN(e820map[i].addr + e820map[i].size, PMD_SIZE);
		e820map[i].addr = ALIGN(e820map[i].addr, PMD_SIZE);
		e820map[i].size = align_end - e820map[i].addr;
	}
}

void __init reserve_vpmem(void)
{
	struct memblock_region *region;

	/* Build up the pseudo e820 table */
	for_each_mem_region(region) {
		u64 start = __pfn_to_phys(memblock_region_memory_base_pfn(region));
		u64 end = __pfn_to_phys(memblock_region_memory_end_pfn(region));

		if (start >= end)
			continue;
		if (memblock_is_nomap(region) || memblock_is_mirror(region))
			e820__range_add(start, end - start, E820_TYPE_RESERVED);
		else
			e820__range_add(start, end - start, E820_TYPE_RAM);
	}
	for_each_reserved_mem_region(region) {
		u64 start = __pfn_to_phys(memblock_region_memory_base_pfn(region));
		u64 end = __pfn_to_phys(memblock_region_memory_end_pfn(region));

		e820__range_add(start, end - start, E820_TYPE_RESERVED);
	}

	sanitize_e820_map(e820.entries, ARRAY_SIZE(e820.entries), &e820.nr_entries);

	/*
	 * Find suitable free memory, mark them as 'VPMEM' in the fake e820 table,
	 * which is needed by vpmem_early_init().
	 * Then, remove these region from memblock list.
	 */
	e820__mark_vpmem();
	/*
	 * After marking, new entries may add to tail of e820,
	 * we should sort it for using it as a ordered table later.
	 */
	sanitize_e820_map(e820.entries, ARRAY_SIZE(e820.entries), &e820.nr_entries);
	/*
	 * Addr add size of the vpmem entries in the fake e820 table should align with 2M,
	 * that is necessary for second kernel to successfully initialize vpmem.
	 */
	align_e820_map(e820.entries, e820.nr_entries);
	vpmem_memblock_remove();
}

static int __init early_init_dt_scan_mem_extends(unsigned long node, const char *uname,
				   int depth, void *data)
{
	const __be32 *prop;
	int len, count;

	prop = of_get_flat_dt_prop(node, "mem-extends", &len);
	if (!prop)
		return 1;

	count = (len / sizeof(__be32)) / 5;
	pr_info("mem-extends prop size: %d\n", len);
	while (count-- > 0) {
		u64 base = dt_mem_next_cell(2, &prop);
		u64 size = dt_mem_next_cell(2, &prop);
		u64 type = dt_mem_next_cell(1, &prop);

		switch (type) {
		case E820_TYPE_VPMEM:
		case E820_TYPE_OSP_NVRAM:
		case E820_TYPE_PBS:
		case E820_TYPE_PCIE_MEM:
		case E820_TYPE_BIOS_MEM:
		case E820_TYPE_BIOS_FLASH:
			memblock_reserve(base, size);
			e820__range_add(base, size, type);
			break;
		default:
			pr_warn("bad mem-extends type: %llu\n", type);
			break;
		}
	}
	return 1;
}

void __init vpmem_early_init_dt(void)
{
	of_scan_flat_dt(early_init_dt_scan_mem_extends, NULL);
}
